import { BaseServices } from "./base.services";
import { APIUrl, APIMethod, RespInfo } from "./request.services";
import { MessagePlugin } from "tdesign-vue-next";
import { appRef } from "@/models/app.ref";
import { ToolInfo } from "@/models/tool";


export class ToolService extends BaseServices {
  private static _ins: ToolService = new ToolService();
  public static get ins(): ToolService {
    return this._ins ? this._ins : this._ins = new ToolService();
  }

  /** 获取工具列表 */
  public list(type?: string): Promise<void> {
    const url = APIUrl.Tool + APIMethod.List;
    const data = { type };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(async (res: RespInfo<ToolInfo>) => {
        appRef.tool.setList(res.list)
        reslove();
      })
    });
  }

  /** 新增一条工具 */
  public add(logo: string, href: string, title: string, type: string, remark: string): Promise<void> {
    const { uid } = appRef.user.data
    const url = APIUrl.Tool + APIMethod.Add;
    const data = { user: uid, logo, href, title, type, remark };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(async (res: RespInfo<ToolInfo>) => {
        appRef.tool.add(res.info)
        MessagePlugin("success", "添加成功");
        reslove();
      })
    });
  }

  /** 修改一条工具 */
  public updated(uid: string, logo: string, href: string, title: string, type: string, remark: string): Promise<void> {
    const url = APIUrl.Tool + APIMethod.Updated;
    const data = { uid, logo, href, title, type, remark };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(async (res: RespInfo<ToolInfo>) => {
        appRef.tool.updated(res.info)
        MessagePlugin("success", "修改成功");
        reslove();
      })
    });
  }

  /** 删除一条工具 */
  public delete(uid: string): Promise<boolean> {
    const url = APIUrl.Tool + APIMethod.Delete;
    const data = { uid };
    return new Promise<boolean>((reslove, reject) => {
      this.request(url, data).then(async (res: RespInfo<void>) => {
        appRef.tool.delete(uid)
        MessagePlugin("success", "删除成功");
        reslove(true);
      })
    });
  }

}

export const toolService: ToolService = ToolService.ins;